//
//  MessageViewController.m
//  jungoo
//
//  Created by Sinbad Flyce on 9/18/12.
//  Copyright (c) 2012 VMODEV. All rights reserved.
//

#import "MessageViewController.h"
#import "NewMessageViewController.h"
#import "ChatMessageViewController.h"
#import "BroadcastViewController.h"
#import "MessageNotifyCenter.h"
#import "Extensions.h"

@implementation MessageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - Private Method

- (UITableViewCell*)createCellFromNib
{
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"MessageView" owner:nil options:nil];
    
    return (id)[views objectAtIndex:0];
}

- (UISearchBar*)createSearchBarFromNib
{
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"MessageView" owner:nil options:nil];
    UISearchBar *searchBar = (id)[views objectAtIndex:1];
    
    searchBar.delegate = self;
    
    return searchBar;
}

- (void)initAppearance
{    
    [self setTitle:@"Messages"];
    [self setBackButtonImageActiveName:@"" 
                          inactiveName:@"back-button" 
                                target:self 
                                action:@selector(back)];
    
    [self setRightButtonImageActiveName:@"" 
                          inactiveName:@"edit-button" 
                                target:self 
                                action:@selector(edit)];
    
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    [self.tableView setBackgroundView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_bg.png"]]];
    [self.tableView setAllowsSelectionDuringEditing:YES];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MessageNotifyCenter sharedMessageNotify].delegate = (id)self;
    
    [JGoUtility showProgressInView:self.view 
                            target:self 
                             title:@"Loading..." 
                          selector:@selector(delayLoadMessages:)];
}

- (void)asyncLoadAvatars
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
    
    dispatch_async(queue, ^{
        
        for (NSDictionary *aMessage in masterDataSource) {
            
            NSDictionary *lastMessage = [aMessage objectForKey:@"last_message"];
            
            if ([lastMessage isKindOfClass:[NSDictionary class]]) {
                
                NSDictionary *aSender = [lastMessage objectForKey:@"sender"];
                
                if ([aSender isKindOfClass:[NSDictionary class]]) {
                    
                    NSString *senderAvatarURL = [aSender objectForKey:@"thumb"];
                    NSString *senderId = [aSender objectForKey:@"user_id"];
                    
                    if ([[JGoUtility sharedCachedAvatars] objectForKey:senderId] == nil) {
                        
                        UIImage *senderAvatar = [JGoAPI downloadAvatar:senderAvatarURL error:nil];
                        [[JGoUtility sharedCachedAvatars] setValue:senderAvatar forKey:senderId];
                        [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
                    }
                }
            }
        }
    });    
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initAppearance];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return NO;
}

- (UIButton*)recheckUIFromCell:(UITableViewCell*)cell recheck:(BOOL)check
{
    UIButton *recheckTmp = (id)[cell.contentView viewWithTag:0x100];
    
    if (recheckTmp == nil) {
        recheckTmp = [UIButton buttonWithType:UIButtonTypeCustom];        
    }
    
    [recheckTmp setBackgroundImage:[UIImage imageNamed:check ? @"message-check.png": @"message-uncheck.png"]
                          forState:UIControlStateNormal];
    [recheckTmp addTarget:self action:@selector(recheck:) forControlEvents:UIControlEventTouchUpInside];
    [recheckTmp setFrame:CGRectMake(-27, 22, 27, 27)];
    [recheckTmp setTag:0x100];
    
    return recheckTmp;
}

- (void)changeModeEdit:(BOOL)edit
{
    newMessageUI.hidden = edit;
    broadcastUI.hidden = edit;
    clearUI.hidden = !edit;
    
    [clearUI setTitle:[NSString stringWithFormat:@"Clear all (%d)",[dataSource count]] 
             forState:UIControlStateNormal];
}

- (void)dealloc
{
    [MessageNotifyCenter sharedMessageNotify].delegate = nil;
    [super dealloc];
}

#pragma mark - Action

- (void)back
{
    if ([self.navigationController.viewControllers count] > 1) {
        [[MessageNotifyCenter sharedMessageNotify] setDelegate:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
    else {
        [[MessageNotifyCenter sharedMessageNotify] setDelegate:nil];
        [self dismissModalViewControllerAnimated:YES];
    }
}

- (void)edit
{
    if (self.tableView.editing) {
 
        NSInteger count = 0;
        
        for (NSDictionary *aMessage in dataSource) {
            
            if ([[aMessage objectForKey:@"check"] integerValue] == 1) {
                count++;
            }
        }
        
        if (count == 0) {
            [JGoUtility showAlert:@"Please select one or more items to remove"];
            return;
        }
        
        [JGoUtility showProgressInView:[JGoUtility frontFromView:self.view]
                                target:self
                                 title:@"Deleting..."
                              selector:@selector(delayDelete:)];
    }
    else {
        self.tableView.editing = YES;
        [self setRightButtonImageActiveName:@""
                               inactiveName:@"delete-button" 
                                     target:self 
                                     action:@selector(edit)];   
        [self setBackButtonImageActiveName:@"" 
                              inactiveName:@"cancel-button" 
                                    target:self 
                                    action:@selector(cancel)];
        
        [self changeModeEdit:self.tableView.editing];
        [self.tableView reloadData];
    }
}

- (void)recheck:(UIButton*)sender
{
    
}

- (void)cancel
{
    self.tableView.editing = NO;
    
    [self setRightButtonImageActiveName:@"" 
                           inactiveName:@"edit-button" 
                                 target:self 
                                 action:@selector(edit)];   
    [self setBackButtonImageActiveName:@"" 
                          inactiveName:@"back-button" 
                                target:self 
                                action:@selector(back)];
    
    [self changeModeEdit:NO];
    [self.tableView reloadData];    
}

- (IBAction)newMessage:(id)sender
{
    NewMessageViewController *nmVC = [[[NewMessageViewController alloc] initWithNibName:@"NewMessageViewController" 
                                                                                 bundle:nil] autorelease];
    [self.navigationController pushViewController:nmVC animated:YES];
}

- (IBAction)deleteConversations:(id)sender
{
    [[[[UIAlertView alloc] initWithTitle: @"Alumnee"
								 message: @"Are you sure to want remove all items?"
								delegate: (id)self
					   cancelButtonTitle: @"Yes"
					   otherButtonTitles: @"No",nil] autorelease] show];
}

- (IBAction)broadcast:(id)sender
{
    BroadcastViewController *bcVC = [[[BroadcastViewController alloc] initWithNibName:@"BroadcastViewController"
                                                                                 bundle:nil] autorelease];
    [self.navigationController pushViewController:bcVC animated:YES];
}

#pragma mark - UIAlertDelegate

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        
        [JGoUtility showProgressInView:[JGoUtility frontFromView:self.view]
                                target:self title:@"Deleting..."
                              selector:@selector(delayDeleteAll:)];
    }
}

#pragma mark - UITableView Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return ([dataSource count]);
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MessageLeftCell"];
    NSDictionary *aMessage = [dataSource objectAtIndex:indexPath.row];
    
    if (cell == nil) {
        cell = [self createCellFromNib];
    }
    
    if (tableView.editing) {
        BOOL check = ([[aMessage objectForKey:@"check"] integerValue] == 1);
        [cell.contentView addSubview:[self recheckUIFromCell:cell recheck:check]];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    else {
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];        
    }
    
    NSDictionary *lastMessage = [aMessage objectForKey:@"last_message"];
    NSDate *createdDate = [JGoUtility dateFromString3:[aMessage objectForKey:@"date_created"]];
    CGFloat distance = 0;   
    
    [[cell viewWithTag:1] makeBorderRound];
    [[cell viewWithTag:1] setClipsToBounds:YES];
            
    if (lastMessage == nil || [[lastMessage allKeys] count] == 0) {
        [cell imageViewWithTag:1].image = [[JGoUtility sharedCreateAccount] objectForKey:@"avatar"];         
        [cell titleTextWithTag:2].text = [NSString stringWithFormat:@"%@,",[[JGoUtility sharedCreateAccount] objectForKey:@"name"]];
        distance = [[[JGoUtility sharedCreateAccount] objectForKey:@"distance"] floatValue];
        [cell titleTextWithTag:5].text = [aMessage objectForKey:@"name"];
        [cell imageViewWithTag:6].hidden = NO;
    }
    else {
        NSDictionary *aSender = [lastMessage objectForKey:@"sender"];
        [cell titleTextWithTag:5].text = [lastMessage objectForKey:@"content"];
        
        if ([aSender isKindOfClass:[NSDictionary class]]) {
            
            NSString *senderId = [aSender objectForKey:@"user_id"];
            UIImage *senderAvatar = [[JGoUtility sharedCachedAvatars] objectForKey:senderId];
            
            distance = [[aSender objectForKey:@"distance"] floatValue];
            
            [cell imageViewWithTag:1].image = senderAvatar;
            [cell titleTextWithTag:2].text = [aSender objectForKey:@"name"];
            
            if ([senderId isEqualToString:[[JGoUtility sharedCreateAccount] objectForKey:@"user_id"]]) {
                [cell imageViewWithTag:6].hidden = NO;
            }
            else {
                [cell imageViewWithTag:6].hidden = YES;
            }
                 
        }
    }
            
    [cell titleTextWithTag:3].text = [NSString stringWithFormat:@"%@,",[JGoUtility stringFromDate5:createdDate]];
    [cell titleTextWithTag:4].text = [JGoUtility distanceString:[NSString stringWithFormat:@"%f",distance]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.editing) {
        NSDictionary *aMessage = [dataSource objectAtIndex:indexPath.row];
        NSInteger check = [[aMessage objectForKey:@"check"] integerValue]; 
        check = !check;
        [aMessage setValue:[NSString stringWithFormat:@"%d",check] forKey:@"check"];
        [self.tableView reloadData];
    }
    else {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        NSDictionary *aMessage = [dataSource objectAtIndex:indexPath.row];
        ChatMessageViewController *cmVC = [[[ChatMessageViewController alloc] initWithNibName:@"ChatMessageViewController" 
                                                                                       bundle:nil] autorelease];
        cmVC.conversionId = [aMessage objectForKey:@"id"];
        
        [self.navigationController pushViewController:cmVC animated:YES];
    }
}

/*
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
*/

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 72;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}

#pragma mark - SearchBar Delegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

#pragma mark - Delay Method

- (void)delayLoadMessages:(MBProgressHUD*)progress
{
    NSDictionary *user = [JGoUtility sharedCreateAccount];
    NSString *userId = [user objectForKey:@"user_id"];
    NSError *error = nil;    
    
    NSArray *messages = [JGoAPI getConversationsWithUserId:userId onlyOwner:NO error:&error];
    
    if (!error) {
        dataSource = (id)[messages retain];
        masterDataSource = [dataSource mutableCopy];
        [self.tableView reloadData];
        [self asyncLoadAvatars];
    }
    else {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    
    [progress hide:YES];
}

- (void)delayDelete:(MBProgressHUD*)progress
{
    NSDictionary *user = [JGoUtility sharedCreateAccount];
    NSString *userId = [user objectForKey:@"user_id"];
    NSError *error = nil;
    NSMutableArray *cids = [[NSMutableArray new] autorelease];
    
    for (NSDictionary *aMessage in dataSource) {
        
        if ([[aMessage objectForKey:@"check"] integerValue] == 1) {
            [cids addObject:[aMessage objectForKey:@"id"]];
        }
    }
    
    if ([cids count]) {
        BOOL result = [JGoAPI deleteConversationsWithUserId:userId conversationIds:[cids componentsJoinedByString:@";"] error:&error];
        
        if (result) {
                      
            NSMutableArray *willRemoveItems = [[NSMutableArray new] autorelease];
            
            for (int iMes = 0; iMes < [dataSource count]; iMes++) {
                
                NSDictionary *aMessage = [dataSource objectAtIndex:iMes];
                
                if ([[aMessage objectForKey:@"check"] integerValue] == 1) {
                    [willRemoveItems addObject:aMessage];
                }
            }
            
            for (NSDictionary *aMessage in willRemoveItems) {
                [dataSource removeObject:aMessage];
            }
            
            [self setRightButtonImageActiveName:@""
                                   inactiveName:@"edit-button"
                                         target:self
                                         action:@selector(edit)];
            [self setLeftButtonImageActiveName:@""
                                  inactiveName:@"back-button"
                                        target:self
                                        action:@selector(back)];
            
            self.tableView.editing = NO;
            [self changeModeEdit:self.tableView.editing];
            [self.tableView reloadData];
        }
        else {
            [JGoUtility showAlert:[error localizedDescription]];
        }
    }
    
    [progress hide:YES];
}

- (void)delayDeleteAll:(MBProgressHUD*)progress
{
    NSDictionary *user = [JGoUtility sharedCreateAccount];
    NSString *userId = [user objectForKey:@"user_id"];
    NSError *error = nil;
    NSMutableArray *cids = [[NSMutableArray new] autorelease];
    
    for (NSDictionary *aMessage in dataSource) {                
        [cids addObject:[aMessage objectForKey:@"id"]];
    }
    
    if ([cids count]) {
        BOOL result = [JGoAPI deleteConversationsWithUserId:userId conversationIds:[cids componentsJoinedByString:@";"] error:&error];
        
        if (result) {
            
            [dataSource release];
            dataSource = nil;
            
            [self setRightButtonImageActiveName:@""
                                   inactiveName:@"edit-button"
                                         target:self
                                         action:@selector(edit)];
            [self setLeftButtonImageActiveName:@""
                                  inactiveName:@"back-button"
                                        target:self
                                        action:@selector(back)];
            
            self.tableView.editing = NO;
            [self changeModeEdit:self.tableView.editing];
            [self.tableView reloadData];
        }
        else {
            [JGoUtility showAlert:[error localizedDescription]];
        }
    }
    
    [progress hide:YES];
}

#pragma mark - SearchBar Delegate

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [dataSource release];
    
    if ([searchText length]) {
    
        dataSource = [NSMutableArray new];
        
        for (NSDictionary *aConversation in masterDataSource) {
            
            NSString *curString = nil;
            NSDictionary *lastMessage = [aConversation objectForKey:@"last_message"];
            
            if ([[lastMessage allKeys] count]) {
                curString =  [lastMessage objectForKey:@"content"];
            }
            else {
                curString =  [aConversation objectForKey:@"name"];
            }
            
            
            NSRange substringRange = [curString rangeOfString:searchText options:NSCaseInsensitiveSearch];
            
            if (substringRange.length != 0) {
                [dataSource addObject:aConversation];
            }
        }
    }
    else {
        dataSource = [masterDataSource mutableCopy];
    }
    
    [self.tableView reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

@end
